<template>
  <el-dialog v-model="dialogVisible" title="碳排放数据传递" :width="'800px'">
    <!-- 步骤条 -->
    <div class="steps-container">
      <el-steps class="custom-steps" :active="currentStep" finish-status="success">
        <el-step title="选择类型" :icon="Edit" />
        <el-step title="录入数据" :icon="MessageBox" />
        <el-step title="结果展示" :icon="Check" />
      </el-steps>
    </div>
    <div v-if="currentStep === 0" class="step-content">
      <div class="layer-selection">
        <div class="selection-title">
          <h3>请选择录入的数据类型</h3>
        </div>
        <div class="layer-options">
          <div
            v-for="(layer, index) in layers"
            :key="layer.value"
            class="layer-option"
            :class="{ selected: selectedLayer === layer.value }"
            @click="selectedLayer = layer.value"
          >
            <div class="layer-icon">
              <el-icon :size="24" :color="selectedLayer === layer.value ? '#009688' : '#909399'">
                <component :is="layer.icon" />
              </el-icon>
            </div>
            <div class="layer-info">
              <h4>{{ layer.label }}</h4>
              <p>{{ layer.description }}</p>
            </div>
            <div class="layer-number">{{ index + 1 }}</div>
          </div>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" :disabled="!selectedLayer" @click="nextStep">下一步</el-button>
      </div>
    </div>

    <div v-else-if="currentStep === 1">
      <div v-if="selectedLayer === '1'">
        <el-form>
          <el-form-item label="输入PCF值" class="input-item">
            <el-input
              v-model="inputValue"
              placeholder="请输入PCF值"
              type="number"
              :controls="false"
              @wheel="(e: Event) => (e.target as HTMLInputElement).blur()"
            >
              <template #suffix>
                <span>kgCO₂eq</span>
                <!-- 这里添加单位 -->
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="previewstep">上一步</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </div>
      <div v-else class="step-content">
        <el-form>
          <!-- 第一行：左侧和右侧下拉栏 -->
          <el-row :gutter="0">
            <!-- 将gutter从20减小到10 -->
            <el-col :span="6">
              <el-form-item label="碳排源：" class="input-item">
                <div class="static-text-field">
                  <span>天然气</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="选择碳排放因子来源" class="input-item">
                <el-select v-model="carbonSourceSubtype_NG" placeholder="请选择碳排放因子来源">
                  <el-option
                    v-for="item in subtypeOptions_NG"
                    :key="item.value"
                    :label="item.label"
                    :value="item.factorValue ?? 0"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="请输入AD值" class="input-item">
            <el-input
              v-model="adValueNG"
              placeholder="请输入AD值"
              type="number"
              :controls="false"
              @wheel="(e: Event) => (e.target as HTMLInputElement).blur()"
            >
              <template #suffix>
                <span>m3</span>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-divider class="footer-divider"></el-divider>
        <el-form>
          <!-- 第二行：左侧和右侧下拉栏 -->
          <el-row :gutter="0">
            <!-- 将gutter从20减小到10 -->
            <el-col :span="6">
              <el-form-item label="碳排源：" class="input-item">
                <div class="static-text-field">
                  <span>水</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="选择碳排放因子来源" class="input-item">
                <el-select v-model="carbonSourceSubtype_Water" placeholder="请选择碳排放因子来源">
                  <el-option
                    v-for="item in subtypeOptions_Water"
                    :key="item.value"
                    :label="item.label"
                    :value="item.factorValue ?? 0"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="请输入AD值" class="input-item">
            <el-input
              v-model="adValueWater"
              placeholder="请输入AD值"
              type="number"
              :controls="false"
              @wheel="(e: Event) => (e.target as HTMLInputElement).blur()"
            >
              <template #suffix>
                <span>L</span>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-divider class="footer-divider"></el-divider>
        <el-form>
          <!-- 第三行：左侧和右侧下拉栏 -->
          <el-row :gutter="0">
            <!-- 将gutter从20减小到10 -->
            <el-col :span="6">
              <el-form-item label="碳排源：" class="input-item">
                <div class="static-text-field">
                  <span>柴油</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="选择碳排放因子来源" class="input-item">
                <el-select v-model="carbonSourceSubtype_Diesel" placeholder="请选择碳排放因子来源">
                  <el-option
                    v-for="item in subtypeOptions_Diesel"
                    :key="item.value"
                    :label="item.label"
                    :value="item.factorValue ?? 0"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="请输入AD值" class="input-item">
            <el-input
              v-model="adValueDiesel"
              placeholder="请输入AD值"
              type="number"
              :controls="false"
              @wheel="(e: Event) => (e.target as HTMLInputElement).blur()"
            >
              <template #suffix>
                <span>L</span>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-divider class="footer-divider"></el-divider>
        <el-form>
          <!-- 第四行：左侧和右侧下拉栏 -->
          <el-row :gutter="0">
            <!-- 将gutter从20减小到10 -->
            <el-col :span="6">
              <el-form-item label="碳排源：" class="input-item">
                <div class="static-text-field">
                  <span>电能</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="选择碳排放因子来源" class="input-item">
                <el-select v-model="carbonSourceSubtype_Ele" placeholder="请选择碳排放因子来源">
                  <el-option
                    v-for="item in subtypeOptions_Ele"
                    :key="item.value"
                    :label="item.label"
                    :value="item.factorValue ?? 0"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="请输入AD值" class="input-item">
            <el-input
              v-model="adValueEle"
              placeholder="请输入AD值"
              type="number"
              :controls="false"
              @wheel="(e: Event) => (e.target as HTMLInputElement).blur()"
            >
              <template #suffix>
                <span>kwh</span>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="previewstep">上一步</el-button>
          <el-button type="primary" @click="confirm">下一步</el-button>
        </div>
      </div>
    </div>
    <div v-else>
      <h3>数据录入结果</h3>
      <el-table
        :data="filterTableData"
        style="width: 100%"
        max-height="290px"
        border
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          height: '50px',
          fontWeight: 600
        }"
        :cell-style="{
          height: '45px'
        }"
        :span-method="objectSpanMethod"
      >
        <el-table-column prop="source" label="来源" align="center" />
        <el-table-column prop="key" label="属性" align="center" />
        <el-table-column prop="value" label="值" align="center" />
      </el-table>

      <!-- 数字签名显示区域 -->
      <div v-if="digitalSignature" class="signature-container">
        <div class="signature-label">数字签名：</div>
        <div class="signature-value">{{ digitalSignature }}</div>
      </div>
      <div class="dialog-footer">
        <el-button type="primary" @click="exitBox">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { Edit, MessageBox, Box, Check } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";
const baseUrl = import.meta.env.VITE_BASE_URL;

const dialogVisible = ref(false);
const inputValue = ref("");
const emits = defineEmits(["submit"]); // 声明事件，父组件监听
const currentRow = ref();
const currentStep = ref(0);
const selectedLayer = ref("");
const carbonSourceSubtype_NG = ref("");
const carbonSourceSubtype_Water = ref("");
const carbonSourceSubtype_Diesel = ref("");
const carbonSourceSubtype_Ele = ref("");
const adValueNG = ref("");
const adValueWater = ref("");
const adValueDiesel = ref("");
const adValueEle = ref("");
const emissionFactorList = ref();
const EncryptList = ref();
const layers = [
  {
    label: "PCF (Product Carbon Footprint) - 产品碳足迹",
    icon: Box,
    description: "产品在其整个生命周期中产生的温室气体排放总量(kgCO₂eq)",
    level: 1,
    value: "1"
  },
  {
    label: "AD (Activity Data) - 活动数据",
    level: 2,
    value: "2",
    icon: Box,
    description: "用于计算碳排放的基础数据（电能，水能，天然气，柴油）"
  }
];

const subtypeOptions_NG = computed(() => {
  // 假设factorName: 3代表天然气
  return emissionFactorList.value
    .filter((factor: any) => factor.factorName === 3)
    .map((factor: any) => ({
      value: factor.factorId,
      label: factor.source || "未知来源",
      factorValue: factor.factorValue,
      factorUnit: factor.factorUnit
    }));
});
const subtypeOptions_Water = computed(() => {
  return emissionFactorList.value
    .filter((factor: any) => factor.factorName === 2)
    .map((factor: any) => ({
      value: factor.factorId,
      label: factor.source || "未知来源",
      factorValue: factor.factorValue,
      factorUnit: factor.factorUnit
    }));
});
const subtypeOptions_Diesel = computed(() => {
  return emissionFactorList.value
    .filter((factor: any) => factor.factorName === 4)
    .map((factor: any) => ({
      value: factor.factorId,
      label: factor.source || "未知来源",
      factorValue: factor.factorValue,
      factorUnit: factor.factorUnit
    }));
});
const subtypeOptions_Ele = computed(() => {
  return emissionFactorList.value
    .filter((factor: any) => factor.factorName === 1)
    .map((factor: any) => ({
      value: factor.factorId,
      label: factor.source || "未知来源",
      factorValue: factor.factorValue,
      factorUnit: factor.factorUnit
    }));
});

// 添加到 script 部分的计算属性中
const filterTableData = computed(() => {
  // PCF数据展示
  if (selectedLayer.value === "1") {
    return [{ source: "——", key: "PCF值", value: inputValue.value + " kgCO₂eq" }];
  }
  // AD数据展示
  else {
    const tableData = [];
    // 添加天然气数据
    if (adValueNG.value && carbonSourceSubtype_NG.value) {
      tableData.push(
        { source: "天然气", key: "用量", value: `${adValueNG.value} m³` },
        { source: "天然气", key: "排放因子", value: `${carbonSourceSubtype_NG.value} kgCO₂eq/m³` },
        { source: "天然气", key: "数据承诺", value: EncryptList.value["NGCommitment"] },
        { source: "天然气", key: "数据密文", value: EncryptList.value["NGCipher"] }
      );
    }

    // 添加水资源数据
    if (adValueWater.value && carbonSourceSubtype_Water.value) {
      tableData.push(
        { source: "水资源", key: "用量", value: `${adValueWater.value} L` },
        { source: "水资源", key: "排放因子", value: `${carbonSourceSubtype_Water.value} kgCO₂eq/L` },
        { source: "水资源", key: "数据承诺", value: EncryptList.value["waterCommitment"] },
        { source: "水资源", key: "数据密文", value: EncryptList.value["waterCipher"] }
      );
    }

    // 添加柴油数据
    if (adValueDiesel.value && carbonSourceSubtype_Diesel.value) {
      tableData.push(
        { source: "柴油", key: "用量", value: `${adValueDiesel.value} L` },
        { source: "柴油", key: "排放因子", value: `${carbonSourceSubtype_Diesel.value} kgCO₂eq/L` },
        { source: "柴油", key: "数据承诺", value: EncryptList.value["dieselCommitment"] },
        { source: "柴油", key: "数据密文", value: EncryptList.value["dieselCipher"] }
      );
    }

    // 添加电能数据
    if (adValueEle.value && carbonSourceSubtype_Ele.value) {
      tableData.push(
        { source: "电能", key: "用量", value: `${adValueEle.value} kwh` },
        { source: "电能", key: "排放因子", value: `${carbonSourceSubtype_Ele.value} kgCO₂eq/kwh` },
        { source: "电能", key: "数据承诺", value: EncryptList.value["eleCommitment"] },
        { source: "电能", key: "数据密文", value: EncryptList.value["eleCipher"] }
      );
    }
    return tableData;
  }
});

// 修改单元格合并方法
const objectSpanMethod = ({ row, rowIndex, columnIndex }: { row: any; rowIndex: number; columnIndex: number }) => {
  if (columnIndex != 0) return { rowspan: 1, colspan: 1 };

  const prevRow = filterTableData.value[rowIndex - 1];
  const getSpanCount = (condition: boolean) => {
    if (!condition) return { rowspan: 0, colspan: 0 };
    let count = 0;
    for (let i = rowIndex; i < filterTableData.value.length; i++) {
      const currentRow = filterTableData.value[i];
      if (currentRow.source !== row.source) break;
      count++;
    }
    return { rowspan: count, colspan: 1 };
  };

  return getSpanCount(!prevRow || prevRow.source !== row.source);
};

// 提取数字签名
const digitalSignature = computed(() => {
  // 如果是PCF数据，没有数字签名
  if (selectedLayer.value === "1") {
    return "";
  }
  if (!EncryptList.value || typeof EncryptList.value !== "object" || EncryptList.value["signature"] === undefined) {
    return "加载中...";
  }
  return EncryptList.value["signature"];
});

// 打开弹窗的方法
const openDialog = (row: any) => {
  dialogVisible.value = true;
  currentRow.value = row;
  currentStep.value = 0;
  selectedLayer.value = "0";
  initFormData();
};

const initFormData = async () => {
  try {
    //数据库
    const response = await axios.get(baseUrl + "/api/carbon/getAllFactors");
    console.log("数据列表:", response.data);
    if (response.data && response.data.code === 200) {
      emissionFactorList.value = response.data.data;
      console.log("请求列表:", emissionFactorList.value);
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取请求列表失败";
      console.error("获取请求列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取请求列表出错:", error);
    ElMessage.error("获取请求列表失败，可能是因为参数错误或网络问题");
  }
};

// 确定按钮逻辑
const confirm = async () => {
  if (selectedLayer.value === "1") {
    if (!inputValue.value || inputValue.value === "") {
      // 如果输入框为空，提示用户
      alert("输入框不能为空！");
    } else {
      emits("submit", Number(inputValue.value), currentRow.value); // 将数据传给父组件
      nextStep(); // Move to the next step
    }
  } else {
    // Check that at least one AD value is provided with its emission factor
    const hasValidInput =
      (adValueNG.value && carbonSourceSubtype_NG.value) ||
      (adValueWater.value && carbonSourceSubtype_Water.value) ||
      (adValueDiesel.value && carbonSourceSubtype_Diesel.value) ||
      (adValueEle.value && carbonSourceSubtype_Ele.value);

    if (!hasValidInput) {
      alert("请至少填写一种能源的AD值和对应的碳排放因子！");
      return;
    }

    // Create an object to store all AD data
    const adData = {
      naturalGas: {
        value: adValueNG.value ? parseFloat(adValueNG.value) : 0,
        factor: carbonSourceSubtype_NG.value ? parseFloat(carbonSourceSubtype_NG.value) : 0,
        unit: "m3",
        emission: 0
      },
      water: {
        value: adValueWater.value ? parseFloat(adValueWater.value) : 0,
        factor: carbonSourceSubtype_Water.value ? parseFloat(carbonSourceSubtype_Water.value) : 0,
        unit: "L",
        emission: 0
      },
      diesel: {
        value: adValueDiesel.value ? parseFloat(adValueDiesel.value) : 0,
        factor: carbonSourceSubtype_Diesel.value ? parseFloat(carbonSourceSubtype_Diesel.value) : 0,
        unit: "L",
        emission: 0
      },
      electricity: {
        value: adValueEle.value ? parseFloat(adValueEle.value) : 0,
        factor: carbonSourceSubtype_Ele.value ? parseFloat(carbonSourceSubtype_Ele.value) : 0,
        unit: "kwh",
        emission: 0
      }
    };

    // Calculate emissions for each source
    let totalEmission = 0;

    (Object.keys(adData) as Array<keyof typeof adData>).forEach(key => {
      const source = adData[key];
      if (source.value && source.factor) {
        source.emission = parseFloat((source.value * source.factor).toFixed(4));
        totalEmission += source.emission;
      }
    });
    console.log(totalEmission);
    console.log(adData);
    await EncryptInformation(adData);

    // Save to localStorage for caching
    // localStorage.setItem("adData", JSON.stringify(adData));

    // Emit the data to parent component
    console.log(currentRow.value);
    emits("submit", Number(totalEmission.toFixed(2)), currentRow.value);
    nextStep(); // Move to the next step
  }
};

// 加密信息
const EncryptInformation = async (adData: any) => {
  // console.log(currentRow.value);
  console.log(adData);
  try {
    const response = await axios.post(
      baseUrl + "/api/carbon/encryptADData?projectId=" + currentRow.value.projectId + "&productId=" + currentRow.value.productId,
      adData
    );
    if (response.data && response.data.code !== 200) {
      // 后端返回错误
      console.error("后端错误：", response.data.msg || response.data.message || "未知错误");
    } else {
      // 正常处理
      console.log("请求成功：", response.data);
      EncryptList.value = response.data.data || {};
    }
  } catch (error) {
    // 网络或其他异常
    console.error("请求异常：", error);
  }
};

// 取消按钮逻辑
const cancel = () => {
  inputValue.value = ""; // 清空输入框
  dialogVisible.value = false;
};

const nextStep = () => {
  currentStep.value++;
};

const previewstep = () => {
  currentStep.value = 0;
};

const exitBox = () => {
  // Reset form and close dialog
  adValueNG.value = "";
  adValueWater.value = "";
  adValueDiesel.value = "";
  adValueEle.value = "";
  carbonSourceSubtype_NG.value = "";
  carbonSourceSubtype_Water.value = "";
  carbonSourceSubtype_Diesel.value = "";
  carbonSourceSubtype_Ele.value = "";
  inputValue.value = ""; // 清空输入框
  dialogVisible.value = false;
};

// 暴露方法供父组件调用
defineExpose({ openDialog });
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: right;
  margin-top: 20px; /* 添加上方间距 */
}
.input-item {
  margin-top: 20px; /* 使输入框向下移动 */
}
.steps-container {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 20px 0 5px;
  margin-top: 10px;
}
.custom-steps {
  width: 50%;
}
.custom-steps :deep(.el-step__head.is-process) {
  color: #009688;
  border-color: #009688;
}
.custom-steps :deep(.el-step__head.is-success) {
  color: #009688;
  border-color: #009688;
}
.custom-steps :deep(.el-step__title.is-process) {
  color: #009688;
}
.custom-steps :deep(.el-step__title.is-success) {
  color: #009688;
}
.custom-steps :deep(.el-step__line) {
  background-color: #e6f5f3;
}
.custom-steps :deep(.el-step__line.is-process) {
  background-color: #009688;
}
.custom-steps :deep(.el-step__icon.is-text) {
  background-color: #e6f5f3;
  border-color: #009688;
}
.custom-steps :deep(.el-step__icon.is-text.is-process) {
  background-color: #009688;
}
.custom-steps :deep(.el-step__icon.is-text.is-success) {
  background-color: #009688;
}
.custom-steps :deep(.el-step__icon-inner) {
  font-weight: bold;
}
.custom-steps :deep(.el-step.is-success) .el-step__line {
  background-color: #009688 !important;
}
.layer-selection {
  display: flex;
  flex: 1;
  flex-direction: column;
  align-items: center;
  padding: 5px;
}
.layer-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
  max-width: 600px;
  margin-top: 5px;
}
.layer-option {
  position: relative;
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  background: #ffffff;
  border: 1px solid #e6f5f3;
  border-radius: 8px;
  transition: all 0.3s;
}
.layer-option:hover {
  border-color: #009688;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}
.layer-option.selected {
  background: #e6f5f3;
  border-color: #009688;
}
.layer-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  margin-right: 20px;
  background: #e6f5f3;
  border-radius: 8px;
}
.layer-info {
  flex: 1;
}
.layer-info h4 {
  margin-bottom: 8px;
  font-size: 15px;
  color: #303133;
}
.layer-info p {
  margin: 0;
  font-size: 13px;
  color: #909399;
}
.layer-number {
  margin-left: 20px;
  font-size: 20px;
  font-weight: bold;
  color: #e6f5f3;
}
.layer-option.selected .layer-number {
  color: #009688;
}
.static-text-field {
  display: flex;
  align-items: center;
  height: 32px;
  padding: 0 15px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.03);
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}
.step-content {
  height: 350px; /* 设置固定高度，可以根据需要调整 */
  overflow-y: auto; /* 启用垂直滚动 */
  position: relative;
}
</style>
